package me.stone.stanimeclient.util

import android.content.Context
import android.os.Build
import android.util.Size
import android.view.View
import android.view.ViewGroup
import android.view.WindowInsets
import android.view.WindowManager
import android.view.inputmethod.InputMethodManager
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.core.view.ViewCompat
import androidx.core.view.WindowCompat
import androidx.fragment.app.Fragment
import androidx.lifecycle.LiveData
import androidx.lifecycle.Observer
import androidx.lifecycle.lifecycleScope
import com.didi.drouter.api.DRouter
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayout.OnTabSelectedListener


// Observer<? super T> observer
fun <T, D: LiveData<T>, F: Fragment> F.observe(liveData: D, observer: Observer<T>) {
    liveData.observe(viewLifecycleOwner, observer)
}

fun <T, D: LiveData<T>> AppCompatActivity.observe(liveData: D, observer: Observer<T>) {
    liveData.observe(this, observer)
}


fun <T: TextView> T.hideSoftImm() {
    val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    imm.hideSoftInputFromWindow(windowToken, 0)
    clearFocus()
}


open class DefaultTabSelectedListener: OnTabSelectedListener {

    override fun onTabSelected(tab: TabLayout.Tab?) {}

    override fun onTabUnselected(tab: TabLayout.Tab?) {}

    override fun onTabReselected(tab: TabLayout.Tab?) {}

}

private fun navToFanDetail(detailId: Int, context: Context) {
    DRouter.build("/fan/detail")
        .putExtra("detailId", detailId)
        .start(context) { _ ->
            // debugPrint("result activity is started: ${result.isActivityStarted}")
        }
}

fun <T: Fragment> T.navigationToFanDetail(detailId: Int) {
    navToFanDetail(detailId, requireContext())
}

fun <T: AppCompatActivity> T.navigationToFanDetail(detailId: Int) {
    navToFanDetail(detailId, this)
}


val Context.screenSize: Size
    get() {
        val windowManager = getSystemService(Context.WINDOW_SERVICE) as WindowManager
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {
            val m = windowManager.defaultDisplay
            return Size(m.width, m.height)
        } else {
            val m = windowManager.currentWindowMetrics
            val i = m.windowInsets.getInsetsIgnoringVisibility(
                WindowInsets.Type.systemBars() or WindowInsets.Type.displayCutout()
            )
            val iw = i.left + i.right
            val ih = i.top + i.bottom
            val b = m.bounds
            return Size(b.width() - iw, b.height() - ih)
        }
    }
